package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.yxt.common.sort.MapComparator;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.ListTableAdapter;
import com.yxt.common.ui.TextItemOnClickListener;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Listener;  

/***
 * 咸情信息
 * @author crazyman
 */
public class SaltStationListActivity extends Activity {
	private List<Map<String, String>> datalst = new ArrayList<Map<String, String>>();
	private MapComparator comparator = new MapComparator();
	private String[] from = { "name", "time", "value"};
	private int[] to = {R.id.lbl1,R.id.lbl2,R.id.lbl3};
	private String[] keys = {"code"};
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.salt_list);   //软件activity的布局	
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		TextView lblTitle3 = (TextView)findViewById(R.id.lblTitle3);
		lblTitle3.setOnClickListener(new OnClickListener(){			
			public void onClick(View arg0) {
				fillListView("value");
			}
		});
		initComponent();
	}
	
	private void downloadSaltStationList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new SaltStationHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}	
	}
	
	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		CommConstant.Sever.XIAN_SERVER = server;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"saltlist.xml");
		} else {
			URL url = new URL(server + "Salty/SaltyList.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&tm=");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class SaltStationHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("station".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				datalst.add(data);
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	
	
	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					TextView lblTitle = (TextView)findViewById(R.id.lblTitle);		
					lblTitle.setText(getString(R.string.menu_salt) + "(" + String.valueOf(datalst.size())+ "处)");
					fillListView("");
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadSaltStationList();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void fillListView(String key) {		
		if (!"".equals(key)) {
			comparator.setKey(key);
			Collections.sort(datalst, comparator);
		}
		
		List<Listener> items = new ArrayList<Listener>();
		for (int i = 0; i < from.length; i++) {
			Listener listener = new Listener(to[i],new TextItemOnClickListener(this, SaltStationDetailActivity.class));
			items.add(listener);
		}
		items.add(new Listener(R.id.imgdetail,new TextItemOnClickListener(this, SaltStationChartActivity.class)));
		
		List<String> keylist = new ArrayList<String>();
		for (int i = 0; i < keys.length; i++) {
			keylist.add(keys[i]);
		}
		
		ListTableAdapter adapter = new ListTableAdapter(this,datalst,R.layout.salt_list_item,from,to,items,keylist);
		ListView lstWaterStation = (ListView) findViewById(R.id.lstSaltStation);
		lstWaterStation.setAdapter(adapter);
	}
	
	protected void onDestroy() {     
        super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}